import re, os, logging, sys
import logging.handlers
from .filter import run_filter, get_md5_json
from .stat import run_stat

logger = logging.getLogger('NextApp-ONT-QC')


def run_cell(cell_dir, qscore_cutoff, distribution_step, distribution_endpoint, thread):
    cell_dir = cell_dir.rstrip('/')
    prefix = os.path.basename(cell_dir)
    match = re.match(re.compile(r'^(\d+)[-_](\w+)[-_](\S+)$'), prefix)
    if not match:
        logger.error('''cell文件夹，格式不匹配r'^(\d+)[-_](\w+)[-_](\S+)$': %s''' % cell_dir)
        sys.exit()
    subdirs = os.listdir(cell_dir)
    if len(subdirs) != 1:
        logger.error('''cell文件夹下子目录个数不符合要求（只能一个子目，现有：%d）: %s''' % (len(subdirs), cell_dir))
        sys.exit()
    report_dir = os.path.join(cell_dir, subdirs[0], 'qc_report')
    if not os.path.exists(report_dir): os.makedirs(report_dir)
    log_name = os.path.join(report_dir, 'cell_stats.log')
    if os.path.exists(log_name): os.remove(log_name)
    os.mknod(log_name)
    fh = logging.FileHandler(log_name)
    logger.addHandler(fh)
    summary_file, fastq, summary4stat_tsv, filter_stat = run_filter(cell_dir, report_dir, prefix, thread)
    run_stat(report_dir, summary4stat_tsv, filter_stat, qscore_cutoff, distribution_step, distribution_endpoint)
    get_md5_json(report_dir)


def run_cell_list(cell_list_file, qscore_cutoff, distribution_step, distribution_endpoint, thread):
    fp = open(cell_list_file)
    for line in fp:
        line = line.strip()
        if not line: continue
        if not os.path.exists(line):
            logger.error('''cell文件夹不存在: %s''' % line)
            sys.exit()
        run_cell(line, qscore_cutoff, distribution_step, distribution_endpoint, thread)
    fp.close()
